﻿/*
 * ©2009-2011 XELF
 * http://xelf.info
 */

using System.Runtime.InteropServices;

namespace XELF.Framework {

	[StructLayout(LayoutKind.Explicit)]
	public struct Union32 {
		[FieldOffset(0)]
		public float Single;
		[FieldOffset(0)]
		public int Int32;
	}

	[StructLayout(LayoutKind.Explicit)]
	public struct Union64 {
		[FieldOffset(0)]
		public double Double;
		[FieldOffset(0)]
		public long Int64;
	}

	public partial class MathHelper {
		public static float Rsqrte(float x) {
			var u = new Union32 { Single = x, };
			var xhalf = 0.5f * x;
			u.Int32 = 0x5F3759DF - (u.Int32 >> 1);
			x = u.Single;
			return x * (1.5f - xhalf * x * x);
		}
		public static double Rsqrte(double x) {
			var u = new Union64 { Double = x, };
			var xhalf = 0.5f * x;
			u.Int64 = 0x5FE6EB50C7AA19F9 - (u.Int64 >> 1);
			x = u.Double;
			return x * (1.5f - xhalf * x * x);
		}
		public static float Rsqrt(float x) {
			return 1.0f / Sqrt(x);
		}
		public static double Rsqrt(double x) {
			return 1.0 / System.Math.Sqrt(x);
		}
	}

}
